#!/usr/bin/env python
#!-*- coding:utf-8 -*-
from google.appengine.api import memcache
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db

from datetime import datetime, timedelta
import os
import cgi

import models
import myutils

weekdays_jp = ["月","火","水","木","金","土","日"]

# BigTableからデータを取得しディクショナリに設定
def Get_KintaiDic(userid, fromdate, todate):
    """
    BigTableからデータを取得しディクショナリに設定
    """
    kintai_dic = {}
    kintais = db.GqlQuery("SELECT * FROM Kintai Where userid = :1 and date >= :2 and date <= :3", \
                          userid, fromdate, todate)
    for k in kintais:
        rec_dic = {}
        rec_dic["kaishi"] = k.kaishi.encode('utf-8')
        rec_dic["syuryo"] = k.syuryo.encode('utf-8')
        rec_dic["jitudo"] = k.jitudo.encode('utf-8')
        rec_dic["zan_futu"] = k.zan_futu.encode('utf-8')
        rec_dic["zan_sinya"] = k.zan_sinya.encode('utf-8')
        rec_dic["zan_gokei"] = k.zan_gokei.encode('utf-8')
        rec_dic["comment"] = k.comment.encode('utf-8')
        
        kintai_dic[k.date] = rec_dic

    return kintai_dic

# カレンダー用HTML生成
def Create_Calender_Html(userinfo, date_dt, fromdate, todate, kintai_dic):
    """
    カレンダー用HTML生成
    """
    
    calender_html = ""
    kaishi_name = ""
    syuryo_name = ""
    jitudo_name = ""
    zan_futu_name = ""
    zan_sinya_name = ""
    zan_gokei_name = ""
    comment_name = ""
    rec_dic = {}

    wk_dt = datetime(int(fromdate[0:4]), int(fromdate[4:6]), int(fromdate[6:8]))
    todate_dt = datetime(int(todate[0:4]), int(todate[4:6]), int(todate[6:8]))
    while wk_dt <= todate_dt:
        if wk_dt.weekday() == 5:
            calender_html += '<tr class="row_blue">'
        elif wk_dt.weekday() == 6:
            calender_html += '<tr class="row_red">'
        else:
            calender_html += '<tr>'
                
        wk_str = "%04d%02d%02d" % (wk_dt.year, wk_dt.month, wk_dt.day)                                    
        calender_html += '<td><a href="./?date=%s">%4d/%2d/%2d(%s)</a></td>'  % \
                            ( wk_str, wk_dt.year, wk_dt.month, wk_dt.day, weekdays_jp[wk_dt.weekday()])
                
        try:
            rec_dic = kintai_dic[wk_str]
            
            kaishi_str = rec_dic['kaishi']
            syuryo_str = rec_dic['syuryo']
            jitudo_str = rec_dic['jitudo']
            zan_futu_str = rec_dic['zan_futu']
            zan_sinya_str = rec_dic['zan_sinya']
            zan_gokei_str = rec_dic['zan_gokei']
            comment_str = rec_dic['comment']
            
        except:
            kaishi_str = ''
            syuryo_str = ''
            jitudo_str = ''
            zan_futu_str = ''
            zan_sinya_str = ''
            zan_gokei_str = ''
            comment_str = ''               
    
        if (date_dt.year == wk_dt.year) and (date_dt.month == wk_dt.month) and (date_dt.day == wk_dt.day):

            #
            fieldname = "kaishi%4d%02d%02d" % (wk_dt.year, wk_dt.month, wk_dt.day)
            kaishi_name = fieldname
            wk_str = kaishi_str.encode('utf-8')
            if wk_str == "": wk_str = userinfo.kaishi.encode('utf-8')
            calender_html += '<td><input type="text" id="%s" name="%s" size="6" maxlength="5" value="%s" onkeypress="keypress(event, \'%s\');" /></td>' \
                        % (fieldname, fieldname, wk_str, fieldname)

            fieldname = "syuryo%4d%02d%02d" % (wk_dt.year, wk_dt.month, wk_dt.day)
            syuryo_name = fieldname
            wk_str = syuryo_str.encode('utf-8')
            if wk_str == "": wk_str = userinfo.syuryo.encode('utf-8')
            calender_html += '<td><input type="text" id="%s" name="%s" size="6" maxlength="5" value="%s" onkeypress="keypress(event, \'%s\');" /></td>' \
                        % (fieldname, fieldname, wk_str, fieldname)

            fieldname = "jitudo%4d%02d%02d" % (wk_dt.year, wk_dt.month, wk_dt.day)
            jitudo_name = fieldname
            wk_str = jitudo_str.encode('utf-8')
            if wk_str == "": wk_str = userinfo.jitudo.encode('utf-8')
            calender_html += '<td><input type="text" id="%s" name="%s" size="6" maxlength="5" value="%s" onkeypress="keypress(event, \'%s\');" /></td>' \
                        % (fieldname, fieldname, wk_str, fieldname)

            fieldname = "zan_futu%4d%02d%02d" % (wk_dt.year, wk_dt.month, wk_dt.day)
            zan_futu_name = fieldname
            wk_str = zan_futu_str.encode('utf-8')
            if wk_str == "": wk_str = userinfo.zan_futu.encode('utf-8')
            calender_html += '<td><input type="text" id="%s" name="%s" size="6" maxlength="5" value="%s" onkeypress="keypress(event, \'%s\');" /></td>' \
                        % (fieldname, fieldname, wk_str, fieldname)
                        
            fieldname = "zan_sinya%4d%02d%02d" % (wk_dt.year, wk_dt.month, wk_dt.day)
            zan_sinya_name = fieldname
            wk_str = zan_sinya_str.encode('utf-8')
            if wk_str == "": wk_str = userinfo.zan_sinya.encode('utf-8')
            calender_html += '<td><input type="text" id="%s" name="%s" size="6" maxlength="5" value="%s" onkeypress="keypress(event, \'%s\');" /></td>' \
                        % (fieldname, fieldname, wk_str, fieldname)

            fieldname = "zan_gokei%4d%02d%02d" % (wk_dt.year, wk_dt.month, wk_dt.day)
            zan_gokei_name = fieldname
            wk_str = zan_gokei_str.encode('utf-8')
            if wk_str == "": wk_str = userinfo.zan_gokei.encode('utf-8')
            calender_html += '<td><input type="text" id="%s" name="%s" size="6" maxlength="5" value="%s" onkeypress="keypress(event, \'%s\');"/></td>' \
                        % (fieldname, fieldname, wk_str, fieldname)

            fieldname = "comment%4d%02d%02d" % (wk_dt.year, wk_dt.month, wk_dt.day)
            comment_name = fieldname
            calender_html += '<td  class=\"comment\"><input type="text" id="%s" name="%s" size="34" maxlength="30" value="%s" onkeypress="keypress(event, \'%s\');" /></td>' \
                        % (fieldname, fieldname, comment_str, fieldname)
            
            calender_html += '<td><input type="button" id="enter" value="登録" onclick="check()" /><input type="reset" id="reset" value="リセット"/></td>'
            calender_html += "</tr>"
        else:
            calender_html += "<td>%s</td>" % kaishi_str.encode('utf-8')
            calender_html += "<td>%s</td>" % syuryo_str.encode('utf-8')
            calender_html += "<td>%s</td>" % jitudo_str.encode('utf-8')
            calender_html += "<td>%s</td>" % zan_futu_str.encode('utf-8')
            calender_html += "<td>%s</td>" % zan_sinya_str.encode('utf-8')
            calender_html += "<td>%s</td>" % zan_gokei_str.encode('utf-8')
            calender_html += "<td class=\"comment\">%s</td>" % comment_str

            calender_html += "<td></td>"
            calender_html += "</tr>"

        # １日進める
        wk_dt = wk_dt + timedelta(days=1)

    return calender_html, kaishi_name, syuryo_name, jitudo_name, zan_futu_name, zan_sinya_name, zan_gokei_name, comment_name

# カレンダー
class MainHandler(webapp.RequestHandler):
    """
    カレンダー
    """
    def get(self):

        us = myutils.Get_UserSession(self.request.cookies)
        if us == None: return self.redirect("/Login")
        
        # UserSessionあり
        ui = myutils.Get_UserInfo(us.userid)
        if ui == None: return self.redirect("/Login")
        
        date_dt, date_str = myutils.Get_Date(self.request)
        fromdate_str, todate_str = myutils.Get_FromTo(str(ui.shimebi), date_str)
        prevmonth_str = myutils.Get_FeedMonth(date_str, -1)
        nextmonth_str = myutils.Get_FeedMonth(date_str, 1)

        kd = Get_KintaiDic(ui.userid, fromdate_str, todate_str)
        calender_html = ""
        kaishi_field = ""
        syuryo_field = ""
        jitudo_field = ""
        zan_futu_field = ""
        zan_sinya_field = ""
        zan_gokei_field = ""
        comment_field = ""

        calender_html, \
        kaishi_field, \
        syuryo_field, \
        jitudo_field, \
        zan_futu_field, \
        zan_sinya_field, \
        zan_gokei_field, \
        comment_field \
         = Create_Calender_Html(ui, date_dt, fromdate_str, todate_str, kd)
        template_values = {
              'prevmonth_str': prevmonth_str,
              'thismonth_str': date_str,
              'nextmonth_str': nextmonth_str,
              'date_str': date_str,
              'calender_html': calender_html,
              'kaishi_field': kaishi_field,
              'syuryo_field': syuryo_field,
              'jitudo_field': jitudo_field,
              'zan_futu_field': zan_futu_field,
              'zan_sinya_field': zan_sinya_field,
              'zan_gokei_field':zan_gokei_field,
              'comment_field': comment_field
        }

        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        self.response.out.write(template.render(path, template_values))

    def post(self):
        us = myutils.Get_UserSession(self.request.cookies)
        if us == None: return self.redirect("/Login")
        # UserSessionあり
        ui = myutils.Get_UserInfo(us.userid)
        if ui == None: return self.redirect("/Login")
        
        userid_str = ui.userid.encode('utf-8')
        date_dt, date_str = myutils.Get_Date(self.request)        
        
        # 削除
        kintais = db.GqlQuery("SELECT * FROM Kintai Where userid = :1 and date = :2", userid_str, date_str)
        try:
            for k in kintais: k.delete()
        finally:

            name_str = "kaishi%s" % date_str
            kaishi_str = cgi.escape(self.request.get(name_str))
               
            name_str = "syuryo%s" % date_str
            syuryo_str = cgi.escape(self.request.get(name_str))
    
            name_str = "jitudo%s" % date_str
            jitudo_str = cgi.escape(self.request.get(name_str))
            
            name_str = "comment%s" % date_str
            comment_str = cgi.escape(self.request.get(name_str))   

            if kaishi_str <> "" or syuryo_str <> "" or jitudo_str <> "" or comment_str <> "":

                kintai = models.Kintai(userid = userid_str, \
                                       date   = date_str, \
                                       kaishi = kaishi_str, \
                                       syuryo = syuryo_str, \
                                       jitudo = jitudo_str)
                
                name_str = "zan_futu%s" % date_str
                kintai.zan_futu = cgi.escape(self.request.get(name_str))
        
                name_str = "zan_sinya%s" % date_str
                kintai.zan_sinya = cgi.escape(self.request.get(name_str))
        
                name_str = "zan_gokei%s" % date_str
                kintai.zan_gokei = cgi.escape(self.request.get(name_str))
        
                name_str = "comment%s" % date_str
                kintai.comment = cgi.escape(self.request.get(name_str))   
     
                kintai.put()
            
            self.redirect("/?date=%s" % date_str)

# 一括作成
class SetInitial(webapp.RequestHandler):
    
    def get(self):
        us = myutils.Get_UserSession(self.request.cookies)
        if us == None: return self.redirect("/Login")
        # UserSessionあり
        ui = myutils.Get_UserInfo(us.userid)
        if ui == None: return self.redirect("/Login")
        
        date_dt, date_str = myutils.Get_Date(self.request)
        backmonth_str = date_str
        fromdate_str, todate_str = myutils.Get_FromTo(str(ui.shimebi), date_str)
                
        template_values = {
              'backmonth_str': backmonth_str,
              'fromtodate_str': "%s/%s/%s〜%s/%s/%s" % \
                                  (fromdate_str[0:4], fromdate_str[4:6], fromdate_str[6:8], todate_str[0:4], todate_str[4:6], todate_str[6:8]),
              'userinfo':ui,
              'fromdate_str': fromdate_str,
              'todate_str': todate_str
        }

        path = os.path.join(os.path.dirname(__file__), 'templates/setinitial.html')
        self.response.out.write(template.render(path, template_values))
        
    def post(self):
        us = myutils.Get_UserSession(self.request.cookies)
        if us == None: return self.redirect("/Login")
        # UserSessionあり
        ui = myutils.Get_UserInfo(us.userid)
        if ui == None: return self.redirect("/Login")
 
        date_dt, date_str = myutils.Get_Date(self.request)
        backmonth_str = date_str
        fromdate_str, todate_str = myutils.Get_FromTo(str(ui.shimebi), date_str)

        wk_dt = datetime(int(fromdate_str[0:4]), int(fromdate_str[4:6]), int(fromdate_str[6:8]))
        todate_dt = datetime(int(todate_str[0:4]), int(todate_str[4:6]), int(todate_str[6:8]))
        while wk_dt <= todate_dt:
            if wk_dt.weekday() < 5:
                # 削除
                date_str = "%04d%02d%02d" % (wk_dt.year, wk_dt.month, wk_dt.day)
                kintais = db.GqlQuery("SELECT * FROM Kintai Where userid = :1 and date = :2", ui.userid, date_str)
                try:
                    for k in kintais: k.delete()
                finally:
                    # 追加
                    kintai = models.Kintai(userid = ui.userid, date = date_str)

                    kintai.kaishi = cgi.escape(self.request.get("kaishi"))
                    kintai.syuryo = cgi.escape(self.request.get("syuryo"))
                    kintai.jitudo = cgi.escape(self.request.get("jitudo"))
                    kintai.zan_futu = cgi.escape(self.request.get("zan_futu"))
                    kintai.zan_sinya = cgi.escape(self.request.get("zan_sinya"))
                    kintai.zan_gokei = cgi.escape(self.request.get("zan_gokei"))
                    kintai.comment = cgi.escape(self.request.get("comment"))
                    
                    kintai.put()

            # １日進める
            wk_dt = wk_dt + timedelta(days=1)
        
        if not us: template_values = {'crud': u"作成"}
        else: template_values = {'crud': u"作成"}
        
        path = os.path.join(os.path.dirname(__file__), 'templates/mess_usercommit.html')
        self.response.out.write(template.render(path, template_values))

# CSV出力
class GetCsv(webapp.RequestHandler):

    def get(self):
        # ログインしているか判定し、ログインしていない場合ログイン画面へ
        us = myutils.Get_UserSession(self.request.cookies)
        if us == None: return self.redirect("/Login")
        # UserSessionあり
        ui = myutils.Get_UserInfo(us.userid)
        if ui == None: return self.redirect("/Login")
        
        date_dt, date_str = myutils.Get_Date(self.request)
        fromdate_str, todate_str = myutils.Get_FromTo(str(ui.shimebi), date_str)
        prevmonth_str = myutils.Get_FeedMonth(date_str, -1)
        nextmonth_str = myutils.Get_FeedMonth(date_str, 1)        
        
        backmonth_str = date_str
        fromyear_str = fromdate_str[0:4]
        frommonth_str = fromdate_str[4:6]
        fromdate_str = fromdate_str[6:8]
        toyear_str = todate_str[0:4]
        tomonth_str = todate_str[4:6]
        todate_str = todate_str[6:8]

        template_values = {
              'backmonth_str': backmonth_str,
              'fromyear_str': fromyear_str,
              'frommonth_str': frommonth_str,
              'fromdate_str': fromdate_str,
              'toyear_str': toyear_str,
              'tomonth_str': tomonth_str,
              'todate_str': todate_str,
        }

        path = os.path.join(os.path.dirname(__file__), 'templates/getcsv.html')
        self.response.out.write(template.render(path, template_values))

# 出力
class CsvDownload(webapp.RequestHandler):

    def get(self):
        # ログインしているか判定し、ログインしていない場合ログイン画面へ
        us = myutils.Get_UserSession(self.request.cookies)
        if us == None: return self.redirect("/Login")
        
        import csv
        from StringIO import StringIO
        
        year_from  = cgi.escape(self.request.get("year_from")).encode('utf-8')
        month_from = cgi.escape(self.request.get("month_from")).encode('utf-8')
        day_from   = cgi.escape(self.request.get("day_from")).encode('utf-8')
        year_to    = cgi.escape(self.request.get("year_to")).encode('utf-8')
        month_to   = cgi.escape(self.request.get("month_to")).encode('utf-8')
        day_to     = cgi.escape(self.request.get("day_to")).encode('utf-8')

        date_from = "%4d%02d%02d" % (int(year_from), int(month_from), int(day_from))
        date_to   = "%4d%02d%02d" % (int(year_to), int(month_to), int(day_to))
        
        # use a StringIO buffer rather than opening a file
        output = StringIO()
        w = csv.writer(output)
        row = []
        row.append(u"日".encode('cp932'))
        row.append(u"作業開始".encode('cp932'))
        row.append(u"作業終了".encode('cp932'))
        row.append(u"実働時間".encode('cp932'))
        row.append(u"普通残業".encode('cp932'))
        row.append(u"深夜残業".encode('cp932'))
        row.append(u"残業合計".encode('cp932'))
        row.append(u"有休消化等".encode('cp932'))
        w.writerow(row)

        for d in (range(int(date_from), int(date_to) + 1)):
            row = []
            gqldate_str = ""
            try:
                wk_date = datetime(int(str(d)[0:4]), int(str(d)[4:6]), int(str(d)[6:8]))
                gqldate_str = "%04d%02d%02d" % (wk_date.year, wk_date.month, wk_date.day)

                kintai = db.GqlQuery("SELECT * FROM Kintai Where userid = :1 and date = :2", us.userid, gqldate_str)
                for k in kintai:
                    row.append(k.date.encode('cp932'))
                    row.append(k.kaishi.encode('cp932'))
                    row.append(k.syuryo.encode('cp932'))
                    row.append(k.jitudo.encode('cp932'))
                    row.append(k.zan_futu.encode('cp932'))
                    row.append(k.zan_sinya.encode('cp932'))
                    row.append(k.zan_gokei.encode('cp932'))
                    row.append(k.comment.encode('cp932'))
            except:
                continue
                            
            if not row:
                row.append(gqldate_str)
                row.append("")
                row.append("")
                row.append("")
                row.append("")
                row.append("")
                row.append("")
                row.append("")
            
            w.writerow(row)
            
        # rewind the virtual file
        output.seek(0)
        
        self.response.headers["Content-Type"] = "application/text"
        self.response.out.write(output.read())     

# ログアウト
class LogoutHandler(webapp.RequestHandler):
    """
    ログアウト
    """
    def get(self):
        #セッションの削除
        myutils.Delete_UserSession(self.request.cookies, self.response)
        
        return self.redirect("/")

def main():
    application = webapp.WSGIApplication([('/', MainHandler),
                                          ('/SetInitial', SetInitial),
                                          ('/GetCsv', GetCsv),
                                          ('/Download.csv', CsvDownload),                                          
                                          ('/Logout', LogoutHandler)],
                                         debug=True)
    util.run_wsgi_app(application)

if __name__ == "__main__":
  main()